package com.study.lxy.javaio;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;

public class StreamToByteArray {



    public static void main(String[] args) throws Exception {
        long before = System.currentTimeMillis();
        for (int i = 0; i < 1000 ; i++) {
            InputStream inputStream = new FileInputStream("D:/file_1kb.txt");
            byte[] bytes = StreamToByteArray.readToBytes(inputStream);
            //System.out.println(new String(bytes));
        }
        System.out.println("cost : " + (System.currentTimeMillis() - before));
    }

    /**
     * 使用ByteArrayOutputStream存储读取的流数据，测试读取1000次本地文件(大小为1KB)耗时62ms
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static byte[] readToBytes(InputStream inputStream) throws Exception {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(inputStream.available());
        byte[] data = new byte[1024];
        int len = -1;
        while ((len = inputStream.read(data)) != -1) {
            bos.write(data, 0, len);
        }
        return bos.toByteArray();
    }

    /**
     * 使用byte[]存储读取的流数据，测试读取1000次本地文件(大小为1KB)耗时47ms
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static byte[] readToBytesNew(InputStream inputStream) throws Exception {
        byte[] data = new byte[inputStream.available()];
        inputStream.read(data);
        return data;
    }


}

